package cn.xuqiudong.demo.generate.deferred.service;

import cn.xuqiudong.common.base.model.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.async.DeferredResult;

import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述:
 * @author Vic.xu
 * @since 2023-03-17 13:57
 */
public class DeferredResultService {

    @Autowired
    private TestService testService;

    private Executor executor = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(200));

    public DeferredResult<BaseResponse<?>> buildDeferred(){

        //超时时间
        long timeoutValue = 5000L;
        Map<String, Object> data = new HashMap<>();
        long start = System.currentTimeMillis();
        data.put("startTime:", LocalTime.now());
        data.put("msg", "超时了");
        DeferredResult<BaseResponse<?>> result = new DeferredResult(timeoutValue,BaseResponse.success(data));
        executor.execute(new DeferredRunnable(result));
        return result;
    }

    private static long geInterval(long start){
        return System.currentTimeMillis() - start;
    }

    class DeferredRunnable implements Runnable {

        private DeferredResult<BaseResponse<?>> result;

        public DeferredRunnable(DeferredResult<BaseResponse<?>> result ){
            this.result = result;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                result.setResult(BaseResponse.success("success:" + testService.doSomething()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

